package com.myeasyexcel.service.Impl;


import cn.hutool.core.bean.BeanUtil;
import com.myeasyexcel.mapper.UserMapper;
import com.myeasyexcel.pojo.DTO.UserDto;
import com.myeasyexcel.pojo.entity.User;
import com.myeasyexcel.utils.ExcelCheckResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.ArrayList;
import java.util.List;

/**
 * 监听实际数据校验
 */
@Service
@RequiredArgsConstructor
public class UserImportService{
    private final UserMapper userMapper;

    public  ExcelCheckResult<UserDto> checkImportExcel(@RequestBody List<UserDto> list) {
        for (UserDto user : list) {
            System.out.println(user);
        }

        int size = 0;
        List<UserDto> errorList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            size = this.checkWarehouseImport(list, errorList);
        }
        ExcelCheckResult<UserDto> userDtoExcelCheckResult = new ExcelCheckResult<>();
        userDtoExcelCheckResult.setErrDtos(errorList);
        userDtoExcelCheckResult.setSuccessSize(size);
        return userDtoExcelCheckResult;
    }

    private int checkWarehouseImport(List<UserDto> list, List<UserDto> errorList) {
        int successSize = 0;
        for (UserDto userDto : list) {
            //进行信息校验

            User user = BeanUtil.copyProperties(userDto, User.class);
            userMapper.insert(user);
            //...
            //错误信息直接排除
            //正确的信息可以添加到数据库中
            successSize++;
        }


        return successSize;
    }
}